package com.qf.client;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: dqall
 * @Date: 2018/11/26 12:06
 * @Author: yuemingyang
 * @Description:
 */
public class GetPostTest {
    public static void main(String[] args) {
        //getTest();
        postTest();
    }

    private static void getTest() {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet get = new HttpGet("http://www.baidu.com");
        try {
            CloseableHttpResponse execute = httpClient.execute(get);
            HttpEntity entity = execute.getEntity();
            String toString = EntityUtils.toString(entity, "utf-8");
            System.out.println(toString);
            execute.close();
            httpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private static void postTest() {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost("http://localhost:8081/rest/test");
        String charset = "utf-8";
        List<NameValuePair> parameters = new ArrayList<>();
        parameters.add(new BasicNameValuePair("name", "测试"));
        parameters.add(new BasicNameValuePair("addr", "没想到吧"));
        try {
            HttpEntity enty = new UrlEncodedFormEntity(parameters, charset);
            post.setEntity(enty);
            CloseableHttpResponse execute = httpClient.execute(post);
            HttpEntity entity = execute.getEntity();
            String toString = EntityUtils.toString(entity, "utf-8");
            System.out.println(toString);
            execute.close();
            httpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
